//
//  UserAccount.swift
//  ZHTQWeibo
//
//  Created by ZHTQ on 2018/9/17.
//  Copyright © 2018年 ZHTQ. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    /// 授权令牌
    var access_token: String?
    /// 过期秒数
    var expires_in: Int = 0
    /// 登录用户id
    var uid: String?
    /// 过期时间
    var expires_date: Date?
    /// 用户昵称
    var screen_name: String?
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    
    init(dict: [String: Any]){
        super.init()
        access_token = dict["access_token"] as? String
        expires_in = dict["expires_in"] as! Int
        uid = dict["uid"] as? String
        
        expires_date = Date(timeIntervalSinceNow: TimeInterval(expires_in))
    }
    
    /// kvc 找不到的值忽略
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        
        return "\(self.avatar_large)"
    }
    
    // MARK:- 外部控制方法
    /// 加载用户信息
    func loadUserAccountInfo(finished: @escaping (_ obj: [String: Any]?, _ error: Error?) -> ()) {
        
        //断言 必须要有授权信息才能 获取用户啊信息
        assert(access_token != nil, "必须授权后才能使用")
        assert(uid != nil, "必须授权后才能使用")
        
        //准备请求数据参数
        let parameters = ["access_token": access_token!, "uid": uid!]
        
        //发送请求
        NetworkTools.sharedInstance.get("2/users/show.json", parameters: parameters, progress: { (progress) in
        
        }, success: { (task, obj) in
            
            guard let dict = obj as? [String: Any] else {
                return
            }
            
            // 赋值用户信息
            self.screen_name = dict["screen_name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            ZHLog(dict)
            
            finished(dict,nil)
            
        }) { (task, error) in
            
            finished(nil,error)
        }
        
    }
    /// 保存授权信息
    func saveUserAccount(){
        if !NSKeyedArchiver.archiveRootObject(self, toFile: "userAccount.plist".cachesDict()) {
            ZHLog("userAccount.plist 归档不成功")
        }
        
    }
    /// 缓存对象账户
    static var account: UserAccount?
    
    /// 加载账户
    class func loadUserAccount() -> UserAccount?{
        // 是否缓存了账户
        if UserAccount.account != nil {
            
            return UserAccount.account
        }
        
        // 未缓存账户
        guard let user = NSKeyedUnarchiver.unarchiveObject(withFile: "userAccount.plist".cachesDict()) as? UserAccount else{
            
            return nil
        }

        // 判断授权是否过期
        if user.expires_date?.compare(Date()) != ComparisonResult.orderedDescending {
            ZHLog("guoqi")
            
            return nil
        }
        // 缓存账户
        UserAccount.account = user
        return user
    }
    
    class func deleteUserAccount() -> Bool{
        
        do {
            try FileManager.default.removeItem(atPath: "userAccount.plist".cachesDict())
            return true
        } catch {
            
            return false
        }
    }
    
    
    /// 是否登录
    class func isLogin() -> Bool{
        return UserAccount.loadUserAccount() != nil
    }
    
    
    
    // MARK:- NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(expires_in, forKey: "expires_in")
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expires_date, forKey: "expires_date")
        aCoder.encode(screen_name, forKey: "screen_name")
        aCoder.encode(avatar_large, forKey: "avatar_large")
    }
    
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        uid = aDecoder.decodeObject(forKey: "uid") as? String
        expires_in = aDecoder.decodeInteger(forKey: "expires_in")
        expires_date = aDecoder.decodeObject(forKey: "expires_date") as? Date
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
    }
}
